import os
import time
import json
import datetime
import django_excel as excel
from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.http import HttpResponseRedirect, HttpResponse, FileResponse
from django.http import StreamingHttpResponse
from django.http import JsonResponse
from django.urls import reverse
from django.utils.encoding import escape_uri_path
from django.db.models import Avg, Max, Min, Count, Sum
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from pure_pagination import Paginator, PageNotAnInteger
from utils.JsonDateEncoder import JsonDateEncoder
from utils.mixin_utils import LoginRequiredMixin
from utils.form_utils import get_form_errors
from systems.models import UserProfile, OperationLog


def page_not_found(request):
    """定义全局404"""
    response = render(request, '404.html')
    response.status_code = 404
    return response


def page_error(request):
    """定义全局500"""
    response = render(request, '500.html')
    response.status_code = 500
    return response


class IndexView(LoginRequiredMixin, View):
    """首页视图"""

    def get(self, request):
        v_user_sum = UserProfile.objects.filter(is_delete=0, is_superuser=0).count
        v_year = datetime.datetime.today().year
        v_month = datetime.datetime.today().month
        v_day = datetime.datetime.today().day
        v_user_today = UserProfile.objects.filter(is_delete=0, is_superuser=0, create_datetime__year=v_year,
                                                  create_datetime__month=v_month, create_datetime__day=v_day).count
        v_log_sum = OperationLog.objects.all().count
        v_log_error = OperationLog.objects.filter(status=0).count

        # 获取本周的注册用户
        # 当前天 显示当前日期是本周第几天
        cur_time = datetime.datetime.now()  # 如果数据库保存的是UTC时间,程序不会蹦但是会提示你这不是本地时间
        now_time = datetime.datetime.now()
        day_num = cur_time.isoweekday()
        # 计算当前日期所在周一
        monday = (cur_time - datetime.timedelta(days=day_num))
        # 查询一周内的数据
        v_results = UserProfile.objects.filter(is_delete=0, create_datetime__range=(monday, now_time)) \
            .extra(select={'day': "DATE_FORMAT(create_datetime,'%%e')"}).values("day") \
            .annotate(count=Count("id")).order_by()
        v_datas = []
        for v_res in v_results:
            v_datas.append(v_res['count'])

        v_results2 = OperationLog.objects.filter(is_delete=0) \
            .extra(select={'day': "DATE_FORMAT(create_datetime,'%%e')"}).values("day") \
            .annotate(count=Count("id")).order_by()
        v_datas2 = []
        for v_res in v_results2:
            v_datas2.append(v_res['count'])

        return render(request, 'index.html',
                      {'h_user_sum': v_user_sum, 'h_user_today': v_user_today, 'h_log_sum': v_log_sum,
                       'h_log_error': v_log_error, 'h_datas': v_datas, 'h_datas2': v_datas2})


def download_update(request):
    def down_chunk_file_manager(i_file_path, chuck_size=1024):
        """切片下载"""
        with open(i_file_path, "rb") as o_file:
            while True:
                chuck_stream = o_file.read(chuck_size)
                if chuck_stream:
                    yield chuck_stream
                else:
                    break

    file_path = os.path.join(settings.BASE_DIR, 'assets/Release.zip')
    # 适用于小文件下载
    file = open(file_path, 'rb')
    # 适用于大文件下载
    # file = down_chunk_file_manager(file_path)

    # 方法一：使用 HttpResponse
    # response = HttpResponse(file)
    # 方法二：使用 StreamingHttpResponse
    # response = StreamingHttpResponse(file)
    # 方法三：使用 FileResponse
    response = FileResponse(file)

    response['Content-Type'] = 'application/octet-stream'
    file_name = escape_uri_path(os.path.basename(file_path))
    response["Content-Disposition"] = f"attachment;filename={file_name};filename*=UTF-8''{file_name}"
    return response
